from plugins.public import encryption
import datetime
import json
import os
from django.shortcuts import render, HttpResponse, redirect
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font, NamedStyle
from django.db.models import Q
from apps.cmdb import models as db_asset
from apps.rbac import models as db_rabc
from apps.rbac.extra_views import login_check, perms_check
from wsshOps.settings import BASE_DIR
from plugins.public import read_excel, zabbix_api


@login_check
@perms_check
def asset_detail(request, id):
    """查看服务器详细信息"""
    caption = "资产列表"
    asset_obj = db_asset.Asset.objects.get(id=id)
    ip = asset_obj.admin_ip
    try:
        os_obj = db_asset.AssetOsInfo.objects.get(asset_id=asset_obj.id)
        nic_obj = db_asset.NIC.objects.filter(asset_id=asset_obj.id)
        device_obj = db_asset.Devices.objects.filter(asset_id=asset_obj.id)
        mount_obj = db_asset.Mounts.objects.filter(asset_id=asset_obj.id)
    except:
        os_obj = []
        nic_obj = []
        device_obj = []
        mount_obj = []
    return render(request, "asset/asset_detail.html", locals())


@login_check
@perms_check
def set_connect(request):
    """添加连接配置"""
    asset_id = request.POST.get("asset_id")
    asset_obj = db_asset.Asset.objects.get(id=asset_id)
    admin_ip = asset_obj.admin_ip
    login_port = asset_obj.login_port
    login_user = asset_obj.login_user
    login_passwd = asset_obj.login_passwd
    login_id_rsa = asset_obj.login_id_rsa
    connect_method = asset_obj.connect_method

    str_key = db_rabc.Dict.objects.get(dict_key="ENCRYPT_KEY").dict_val
    pc = encryption.prpcrypt(str_key)
    passwd = login_passwd.strip("b").strip("'").encode(encoding="utf-8")
    de_passwd = pc.decrypt(passwd).decode()

    # if connect_method == "SaltStack":
    #     src_file = os.path.join(BASE_DIR, "plugins", "scripts", "salt_install.sh")
    #     dest_file = "/opt/salt_install.sh"
    #     cmd = "sh /opt/salt_install.sh"
    # else:
    #     src_file = os.path.join(BASE_DIR, "plugins", "scripts", "rsakey_add.sh")
    #     dest_file = "/opt/rsakey_add.sh"
    #     cmd = "sh /opt/rsakey_add.sh"
    # tk = connect_config.delay(admin_ip, login_port, login_user, de_passwd, login_id_rsa, src_file, dest_file, cmd,
    #                           connect_method)

    ret = {"status": "True", "info": "同步成功"}
    data = json.dumps(ret)
    return HttpResponse(data)


@login_check
@perms_check
def asset_recycling(request):
    """添加连接配置"""
    asset_id = request.POST.get("asset_id")
    asset_obj = db_asset.Asset.objects.get(id=asset_id)
    asset_obj.asset_status = "RECYCLE"
    asset_obj.asset_msg = '回收-{}'.format(datetime.datetime.now().strftime('%Y%m%d'))
    asset_obj.save()
    try:
        asset_ip = asset_obj.admin_ip
        zbx_url = db_rabc.Dict.objects.get(dict_key="zbx_url").dict_val
        zbx_user = db_rabc.Dict.objects.get(dict_key="zbx_user").dict_val
        zbx_passwd = db_rabc.Dict.objects.get(dict_key="zbx_passwd").dict_val

        # 获取zabbix 当前告警信息
        hostid_ret = zabbix_api.get_host_ip(zbx_url, zbx_user, zbx_passwd,asset_ip)

        hostid = json.loads(hostid_ret)['result'][0]['hostid']
        delete_ret = zabbix_api.del_host(zbx_url, zbx_user, zbx_passwd,hostid)
        print(delete_ret)
    except Exception as e:
        print(e)

    ret = {"status": "True", "info": "已回收"}
    data = json.dumps(ret)
    return HttpResponse(data)


@login_check
@perms_check
def search_asset(request):
    """过滤服务器信息"""
    search_key = request.POST.get('search_key', None)
    idc_id = request.POST.get('idc_id', None)
    group_id = request.POST.get('group_id', None)
    type_id = request.POST.get('type_id', None)

    if request.session['is_superuser'] == "1":
        db_obj = db_asset.Asset.objects.all().order_by('id')
    else:
        role_id = request.session["role_id"]
        role_obj = db_rabc.Role.objects.get(id=role_id)
        db_obj = role_obj.asset.all().order_by('id')

    if search_key:
        host_list = db_obj.filter((Q(admin_ip__icontains=search_key) | Q(asset_msg__icontains=search_key) |
                                   Q(asset_type__icontains=search_key) | Q(asset_model__icontains=search_key) |
                                   Q(asset_status__icontains=search_key))).order_by("-asset_status")
    if idc_id:
        host_list = db_obj.filter(idc_id=idc_id).order_by("-asset_status")

    if group_id:
        host_list = db_obj.filter(asset_group_id=group_id).order_by("-asset_status")

    if type_id:
        host_list = db_obj.filter(asset_type=type_id).order_by("-asset_status")

    phpmyadmin = db_rabc.Dict.objects.get(dict_key="PHPMYADMIN").dict_val
    return render(request, "asset/asset_search.html", locals())



@login_check
@perms_check
def upload_asset(request):
    """导入服务器信息"""
    upload_file = request.FILES.get("upload_file", None)
    filename = os.path.join(BASE_DIR, "statics", "medias", "upload", "asset_template.xlsx")
    file_obj = open(filename, 'wb')
    for chrunk in upload_file.chunks():
        file_obj.write(chrunk)
        file_obj.close()
    data = read_excel.import_host(filename)

    if request.session['is_superuser'] == "1":
        role_obj = None
    else:
        role_id = request.session["role_id"]
        role_obj = db_rabc.Role.objects.get(id=role_id)

    for i in data:
        admin_ip = i[0]
        if admin_ip:
            asset_msg = i[1]
            group_name = i[2]
            idc_name = i[3]
            login_port = i[4]
            login_user = i[5]
            login_passwd = str(i[6])
            connect_method = i[7]
            try:
                idc_obj = db_asset.IDC.objects.get(idc_name=idc_name)
            except:
                idc_obj = db_asset.IDC(idc_name=idc_name, idc_msg=idc_name)
                idc_obj.save()

            idc_id = idc_obj.id

            try:
                group_obj = db_asset.AssetGroup.objects.get(group_name=group_name)
            except:
                group_obj = db_asset.AssetGroup(group_name=group_name, group_msg=group_name)
                group_obj.save()

            group_id = group_obj.id

            # 初始化密钥
            str_key = db_rabc.Dict.objects.get(dict_key="ENCRYPT_KEY").dict_val
            pc = encryption.prpcrypt(str_key)
            aes_passwd = pc.encrypt(login_passwd)

            try:
                asset_obj = db_asset.Asset(admin_ip=admin_ip, asset_arp=admin_ip,
                                           asset_group_id=group_id, idc_id=idc_id, asset_msg=asset_msg,
                                           login_user=login_user,
                                           login_port=login_port, login_passwd=aes_passwd,
                                           connect_method=connect_method)
                asset_obj.save()

                # 角色导入资产，添加资产权限
                if role_obj:
                    role_obj.host.add(asset_obj)

                if connect_method == "SaltStack":
                    src_file = os.path.join(BASE_DIR, "plugins", "scripts", "salt_install.sh")
                    dest_file = "/opt/salt_install.sh"
                    cmd = "sh /opt/salt_install.sh"
                else:
                    src_file = os.path.join(BASE_DIR, "plugins", "scripts", "rsakey_add.sh")
                    dest_file = "/opt/rsakey_add.sh"
                    cmd = "sh /opt/rsakey_add.sh"

                login_id_rsa = None

                # connect_config.delay(admin_ip, login_port, login_user, login_passwd, login_id_rsa, src_file, dest_file,
                #                      cmd,
                #                      connect_method)
                print("添加成功:{}".format(admin_ip))
            except Exception as e:
                print(e)
                continue
    return redirect('/cmdb/asset/')


@login_check
@perms_check
def export_host(request):
    """导出资产"""
    host_obj = db_asset.Asset.objects.all()

    data_list = []

    str_key = db_rabc.Dict.objects.get(dict_key="ENCRYPT_KEY").dict_val
    pc = encryption.prpcrypt(str_key)
    for i in host_obj:
        if i.asset_group:
            group_name = i.asset_group.group_name
        else:
            group_name = "Unknown"

        if i.idc:
            idc_name = i.idc.idc_name
        else:
            idc_name = "Unknown"
        try:
            passwd = pc.decrypt(i.login_passwd.strip("b").strip("'").encode(encoding="utf-8")).decode()
        except:
            passwd = ''

        host_info = [i.admin_ip, i.asset_msg, group_name, idc_name, i.login_port,
                     i.login_user, passwd, i.connect_method, i.asset_status]

        data_list.append(host_info)

    def headStyle():
        ft = Font(size=14, name='SimSun')  # color="0F0F0F"字体颜色,italic=False,是否斜体,字体样式,大小,bold=False是否粗体

        align = Alignment(horizontal="center", vertical="center")  # 居中对齐

        fill = PatternFill("solid", fgColor="FFFF00")  # 背景填充颜色

        # fill = GradientFill(stop=("000000", "FFFFFF")) #背景填充颜色，渐变

        bd = Side(style='thin', color="000000")

        border = Border(left=bd, top=bd, right=bd, bottom=bd)

        mystyle = NamedStyle(name="mystyle")

        mystyle.font = ft
        mystyle.alignment = align
        mystyle.fill = fill
        mystyle.border = border
        return mystyle

    def boderStyle():
        ft = Font(size=12, name='SimSun')  # color="0F0F0F"字体颜色,italic=False,是否斜体,字体样式,大小,bold=False是否粗体

        align = Alignment(horizontal="center", vertical="center")  # 居中对齐

        # fill = PatternFill("solid", fgColor="FFFF00")  # 背景填充颜色

        # fill = GradientFill(stop=("000000", "FFFFFF")) #背景填充颜色，渐变

        bd = Side(style='thin', color="000000")

        border = Border(left=bd, top=bd, right=bd, bottom=bd)

        bdstyle = NamedStyle(name="bdstyle")

        bdstyle.font = ft
        bdstyle.alignment = align
        # mystyle.fill = fill
        # mystyle.border = border

        return bdstyle

    def makeExcel(data_list):
        global statuss
        try:
            base_dir = BASE_DIR
            path_dir = base_dir + '/statics/medias/download/'
            wb = Workbook()
            filename = path_dir + 'cmdb.xlsx'
            ws = wb.active
            ws.title = u'资产清单'
            N = 1
            head = ["IP", "备注", "归属组", "IDC", "购买时间", "到期时间", "远程端口", "管理账号", "账号密码", "管理方式", "连接状态"]
            data_list.insert(0, head)
            head_Style = headStyle()
            boder_Style = boderStyle()
            for i in data_list:
                n = 1
                for j in i:
                    col = get_column_letter(n)
                    ws["%s%d" % (col, N)] = j
                    if N == 1:
                        ws["%s%d" % (col, N)].style = head_Style
                        ws.column_dimensions['%s' % col].width = 18  # 设置列宽
                    else:
                        ws["%s%d" % (col, N)].style = boder_Style
                    n += 1
                N += 1
            ws.row_dimensions[1].height = 30  # 设置行高
            wb.save(filename)
            statuss = 0
        except Exception as e:
            print(e)
            statuss = 1

    makeExcel(data_list)

    if data_list:
        if statuss == 0:
            success = 1
            message = '服务器信息导出成功'
        else:
            success = 0
            message = '服务器信息转表失败'
    else:
        success = 0
        message = '获取服务器信息失败'
    info_json = {'code': success, 'message': message}
    return HttpResponse(json.dumps(info_json, ensure_ascii=False), content_type="application/json")


def zabbix(request):
    action = request.POST.get("action")
    host_id = request.POST.get("host_id")
    zbx_url = db_rabc.Dict.objects.get(dict_key="zbx_url").dict_val
    zbx_user = db_rabc.Dict.objects.get(dict_key="zbx_user").dict_val
    zbx_passwd = db_rabc.Dict.objects.get(dict_key="zbx_passwd").dict_val
    if action == "get":
        # 获取zabbix 当前告警信息
        host_group_ret = zabbix_api.get_host_group(zbx_url, zbx_user, zbx_passwd)
        template_ret = zabbix_api.get_templates(zbx_url, zbx_user, zbx_passwd)
        host_group_list = []

        for i in json.loads(host_group_ret)["result"]:
            host_group_list.append({"id": i["groupid"], "text": i["name"]})

        template_list = []
        for i in json.loads(template_ret)["result"]:
            template_list.append({"id": i["templateid"], "text": i["name"]})

        host_obj = db_asset.Asset.objects.get(id=host_id)

        host_check = zabbix_api.get_host(zbx_url, zbx_user, zbx_passwd, host_obj.assetosinfo_set.first().host_ip)
        tmp_tag_list = []
        group_tag_list = []
        if json.loads(host_check)["result"]:
            for i in json.loads(host_check)["result"][0]["parentTemplates"]:
                tmp_tag_list.append(i["templateid"])
            for i in json.loads(host_check)["result"][0]["groups"]:
                group_tag_list.append(i["groupid"])

        host_info = {"host_ip": host_obj.assetosinfo_set.first().host_ip, "host_msg": host_obj.asset_msg,
                     "admin_ip": host_obj.admin_ip,
                     "group": host_obj.asset_group.group_name, "host_group": host_group_list,
                     "template_list": template_list, "tmp_tag_list": tmp_tag_list, "group_tag_list": group_tag_list}

        data = json.dumps(host_info)
        return HttpResponse(data)
    else:
        host_name = request.POST.get("host_name")
        vs_name = request.POST.get("vs_name")
        zbx_group = request.POST.get("zbx_group")
        zbx_template = request.POST.get("zbx_template")
        zbx_interface = request.POST.get("zbx_interface")
        zbx_port = request.POST.get("zbx_port")

        group_list = []
        for i in json.loads(zbx_group):
            group_list.append({"groupid": i})

        tmp_list = []
        for i in json.loads(zbx_template):
            tmp_list.append({"templateid": i})

        host_check = zabbix_api.get_host(zbx_url, zbx_user, zbx_passwd, host_name)
        if json.loads(host_check)["result"]:
            zbx_host_id = json.loads(host_check)["result"][0]["hostid"]
            params = {
                "hostid": zbx_host_id,
                "host": host_name,
                "name": vs_name,
                "groups": group_list,
                "templates": tmp_list,
            }
            ret = zabbix_api.update_host(zbx_url, zbx_user, zbx_passwd, params)
            ret = {"status": "True", "info": "更新成功:{}".format(ret)}
            data = json.dumps(ret)
        else:
            params = {
                "host": host_name,
                "name": vs_name,
                "interfaces": [{"type": 1, "main": 1, "useip": 1, "ip": zbx_interface, "dns": "", "port": zbx_port}],
                "groups": group_list,
                "templates": tmp_list,
            }
            ret = zabbix_api.create_host(zbx_url, zbx_user, zbx_passwd, params)
            ret = {"status": "True", "info": "添加成功:{}".format(ret)}
            data = json.dumps(ret)
        return HttpResponse(data)
